package com.cloud.product.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cloud.product.constant.ResponseCode;
import com.cloud.product.dao.ProductInfoDao;
import com.cloud.product.dto.CartDTO;
import com.cloud.product.exception.ProductException;
import com.cloud.product.pojo.ProductInfo;
import com.cloud.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductInfoDao productInfoDao;

    /**
     * 扣除库存
     *
     * @param cars 购物车商品信息（id count）
     */
    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> cars) {
        List<ProductInfo> productInfos = productInfoDao.selectList(Wrappers.<ProductInfo>lambdaQuery()
                .in(ProductInfo::getProductId, cars.stream().map(CartDTO::getProductId).collect(Collectors.toList())));
        if (productInfos == null || productInfos.size() == 0 || cars.size() != productInfos.size()) {
            throw new ProductException(ResponseCode.PRODUCT_NOT_EXIST);
        }
        cars.forEach(cartDTO -> {
            ProductInfo info = productInfos.stream().filter(productInfo -> productInfo.getProductId().equals(cartDTO.getProductId())).findAny().get();
            Integer productQuantity = cartDTO.getProductQuantity();
            Integer result = info.getProductStock() - productQuantity;
            if (result < 0) {
                throw new ProductException(ResponseCode.PRODUCT_STOCK_ERROR);
            }else {
                cartDTO.setProductQuantity(result);
            }
        });
        productInfoDao.decreaseStock(cars);
    }
}
